package com.sunxueqi.framework.config;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import javax.sql.DataSource;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;

/**
 * Druid数据源配置
 * 
 * @author Sun
 *
 */
@Configuration
public class DruidConfig {
	
	// 加载application.yml中的Druid配置
		@ConfigurationProperties(prefix = "spring.datasource")
		@Bean
		public DataSource druid() {
			return new DruidDataSource();
		}

		/**
		 * 配置一个web监控的filter
		 * @return
		 */
		@Bean
		public FilterRegistrationBean filterRegistrationBean() {
			FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
			filterRegistrationBean.setFilter(new WebStatFilter());
			
			Map<String,String> initParams = new HashMap<>();
			initParams.put("exclusions", "*.js,*.css");
			filterRegistrationBean.setInitParameters(initParams);
			filterRegistrationBean.setUrlPatterns(Arrays.asList("/*"));
			
			return filterRegistrationBean;
		}
		
		/**
		 * 配置一个管理后台的servlet
		 * @return
		 */
		@Bean
		public ServletRegistrationBean druidServlet() {
			ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
			Map<String,String> initParams = new HashMap<>();
			// 默认只允许本地访问
			initParams.put("loginUsername", "admin");
			initParams.put("loginPassword", "1234");
			initParams.put("allow", "");
			
			servletRegistrationBean.setInitParameters(initParams);
			
			return servletRegistrationBean;
		}

}
